<template>
  <div class="app-container">
    <el-card shadow="never">
      <div slot="header" class="clearfix">
        <el-row :gutter="20">
          <el-col :span="18">
            <h3>我的错题本</h3>
          </el-col>
          <el-col :span="6" class="text-right">
            <el-button type="primary" icon="el-icon-plus" @click="handleCreate">新建错题本</el-button>
          </el-col>
        </el-row>
      </div>

      <el-row :gutter="20">
        <el-col
          v-for="book in bookList"
          :key="book.id"
          :span="8"
          class="mb-20"
        >
          <el-card class="book-card" shadow="hover" :body-style="{ padding: '0px' }">
            <div class="book-cover" :style="{ backgroundImage: `url(${book.coverImage || defaultCover})` }">
              <div class="book-mask">
                <div class="book-actions">
                  <el-button-group>
                    <el-button size="mini" @click.stop="handleEdit(book)">编辑</el-button>
                    <el-button size="mini" @click.stop="handleView(book)">查看</el-button>
                    <el-button size="mini" type="danger" @click.stop="handleDelete(book)">删除</el-button>
                  </el-button-group>
                </div>
              </div>
              <div v-if="book.isDefault" class="book-default-tag">
                <el-tag type="success" size="mini">默认</el-tag>
              </div>
            </div>
            <div style="padding: 14px;">
              <div class="book-title">{{ book.name }}</div>
              <div class="book-desc">{{ book.description || '暂无描述' }}</div>
              <div class="book-stats">
                <span>错题数: {{ book.questionCount || 0 }}</span>
                <span>已掌握: {{ book.masteredCount || 0 }}</span>
              </div>
              <div class="book-footer">
                <el-button
                  v-if="!book.isDefault"
                  size="mini"
                  @click.stop="handleSetDefault(book)"
                >设为默认</el-button>
                <el-button
                  size="mini"
                  type="primary"
                  @click.stop="handleView(book)"
                >开始学习</el-button>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 分页 -->
      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />

      <!-- 新增/编辑对话框 -->
      <el-dialog
        :title="dialogTitle"
        :visible.sync="dialogVisible"
        width="40%"
      >
        <el-form ref="form" :model="form" :rules="rules" label-width="80px">
          <el-form-item label="错题本名称" prop="name">
            <el-input v-model="form.name" placeholder="请输入错题本名称" />
          </el-form-item>
          <el-form-item label="错题本描述" prop="description">
            <el-input
              v-model="form.description"
              type="textarea"
              :rows="3"
              placeholder="请输入错题本描述"
            />
          </el-form-item>
          <el-form-item label="封面图片">
            <el-upload
              class="avatar-uploader"
              action="/api/upload"
              :show-file-list="false"
              :on-success="handleUploadSuccess"
              :before-upload="beforeUpload"
            >
              <img v-if="form.coverImage" :src="form.coverImage" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
          <el-form-item label="设为默认">
            <el-switch v-model="form.isDefault" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </div>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
import { listBooks, pageBooks, createBook, updateBook, deleteBook, setDefaultBook } from '@/api/wrongQuestion'

export default {
  name: 'BookList',
  data() {
    return {
      // 默认封面图
      defaultCover: require('@/assets/images/login-background.jpg'),
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 8
      },
      // 错题本列表
      bookList: [],
      total: 0,
      loading: true,
      // 对话框相关
      dialogVisible: false,
      dialogTitle: '',
      form: {
        id: undefined,
        name: '',
        description: '',
        coverImage: '',
        isDefault: false
      },
      rules: {
        name: [
          { required: true, message: '错题本名称不能为空', trigger: 'blur' },
          { max: 50, message: '长度不能超过50个字符', trigger: 'blur' }
        ],
        description: [
          { max: 200, message: '长度不能超过200个字符', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    // 获取错题本列表
    getList() {
      this.loading = true
      pageBooks(this.$store.state.user.id, this.queryParams.pageNum, this.queryParams.pageSize)
        .then(response => {
          this.bookList = response.rows
          this.total = response.total
          this.loading = false
        })
        .catch(() => {
          this.loading = false
        })
    },
    // 打开创建对话框
    handleCreate() {
      this.dialogTitle = '新建错题本'
      this.dialogVisible = true
      this.resetForm()
    },
    // 打开编辑对话框
    handleEdit(book) {
      this.dialogTitle = '编辑错题本'
      this.dialogVisible = true
      this.form = {
        id: book.id,
        name: book.name,
        description: book.description,
        coverImage: book.coverImage,
        isDefault: book.isDefault
      }
    },
    // 查看错题本
    handleView(book) {
      this.$router.push(`/wrongQuestion/record/list?bookId=${book.id}`)
    },
    // 删除错题本
    handleDelete(book) {
      this.$confirm('确定要删除这个错题本吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteBook(book.id).then(() => {
          this.$message.success('删除成功')
          this.getList()
        })
      })
    },
    // 设为默认错题本
    handleSetDefault(book) {
      setDefaultBook(this.$store.state.user.id, book.id).then(() => {
        this.$message.success('设置成功')
        this.getList()
      })
    },
    // 重置表单
    resetForm() {
      this.form = {
        id: undefined,
        name: '',
        description: '',
        coverImage: '',
        isDefault: false
      }
    },
    // 提交表单
    submitForm() {
      this.$refs.form.validate(valid => {
        if (valid) {
          const formData = { ...this.form, userId: this.$store.state.user.id }
          if (formData.id) {
            updateBook(formData).then(() => {
              this.$message.success('更新成功')
              this.dialogVisible = false
              this.getList()
            })
          } else {
            createBook(formData).then(() => {
              this.$message.success('创建成功')
              this.dialogVisible = false
              this.getList()
            })
          }
        }
      })
    },
    // 上传前校验
    beforeUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG/PNG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    // 上传成功
    handleUploadSuccess(res) {
      this.form.coverImage = res.data.url
    }
  }
}
</script>

<style lang="scss" scoped>
.book-card {
  position: relative;
  height: 380px;
  transition: all 0.3s;

  &:hover {
    transform: translateY(-5px);
    box-shadow: 0 6px 18px 0 rgba(0, 0, 0, 0.1);
  }

  .book-cover {
    height: 180px;
    background-size: cover;
    background-position: center;
    position: relative;

    .book-mask {
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      background-color: rgba(0, 0, 0, 0.5);
      opacity: 0;
      transition: opacity 0.3s;
      display: flex;
      align-items: center;
      justify-content: center;

      .book-actions {
        text-align: center;
      }
    }

    &:hover .book-mask {
      opacity: 1;
    }

    .book-default-tag {
      position: absolute;
      top: 10px;
      right: 10px;
    }
  }

  .book-title {
    font-size: 16px;
    font-weight: bold;
    margin-bottom: 10px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }

  .book-desc {
    color: #666;
    font-size: 14px;
    height: 60px;
    margin-bottom: 15px;
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 3;
    -webkit-box-orient: vertical;
  }

  .book-stats {
    display: flex;
    justify-content: space-between;
    margin-bottom: 15px;
    color: #888;
    font-size: 13px;
  }

  .book-footer {
    display: flex;
    justify-content: space-between;
  }
}

.avatar-uploader {
  ::v-deep .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }

  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
}

.mb-20 {
  margin-bottom: 20px;
}

.text-right {
  text-align: right;
}
</style>
